package com.xyy.saas.payment.callback.core.handler;

import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.impl.JdCreditAdapter;
import com.xyy.saas.payment.adpater.jdCredit.req.JDNotifyReq;
import com.xyy.saas.payment.adpater.jdCredit.req.RepayNotifyReq;
import com.xyy.saas.payment.adpater.jdCredit.resp.LoanInfoResponse;
import com.xyy.saas.payment.common.model.Tuple2;
import com.xyy.saas.payment.converter.PayCommonConverter;
import com.xyy.saas.payment.dao.model.LoanRepayPlanDetailPo;
import com.xyy.saas.payment.dao.model.LoanRepayPlanPo;
import com.xyy.saas.payment.manager.PayManager;
import com.xyy.saas.payment.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liujf
 * 还款通知处理handler
 */
@Slf4j
@Component
public class JDRepayCallbackHandler extends JDCallbackHandler<RepayNotifyReq> {
    @Resource
    private JdCreditAdapter jdCreditAdapter;

    @Resource
    private PayManager payManager;
    @Value("${jdCredit.repayNotice.switch:true}")
    private Boolean repayNoticeSwitch;

    @Override
    public String getMethod() {
        return "repayNotice";
    }

    @Override
    public JDNotifyReq parseRequest(String content) {
        return JSON.parseObject(content, RepayNotifyReq.class);
    }

    @Override
    public String createLockKey(String bizNo) {
        return RedisUtil.JD_CREDIT_REPAY_NOTIFY + bizNo;
    }

    /**
     * 用于更新京东采购金融的还款计划
     */
    @Override
    public void doHandle(RepayNotifyReq repayNotifyReq) {
        if (Boolean.FALSE.equals(repayNoticeSwitch)) {
            return;
        }
        StopWatch sw = new StopWatch("JDRepayCallbackHandler" + repayNotifyReq.getOrderCode());

        // 回查还款计划
        sw.start("queryLoanDetail");
        LoanInfoResponse response = jdCreditAdapter.queryLoanDetail(null, repayNotifyReq.getOrderCode());
        sw.stop();

        // 更新还款计划
        sw.start("queryRepayPlan");
        Tuple2<LoanRepayPlanPo, List<LoanRepayPlanDetailPo>> tuple2 = payManager.queryRepayPlanAndDetails(repayNotifyReq.getOrderCode());
        sw.stop();

        // 构造更新数据
        LoanRepayPlanPo updateRepayPlanPo = PayCommonConverter.buildUpdateRepayPlanPo(response, tuple2.getT1());
        List<LoanRepayPlanDetailPo> updatePlanDetailList = PayCommonConverter.buildUpdatePlanDetailList(response, tuple2.getT2());


        // 持久化
        sw.start("updateRepayPlan");
        payManager.updateRepayPlan(updateRepayPlanPo, updatePlanDetailList);
        sw.stop();

        log.info("JDRepayCallbackHandler#doHandle req:{},sw:{}", JSON.toJSONString(repayNotifyReq), sw.prettyPrint());

    }
}
